package com.ruoyi.iot.config;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.reflections.Reflections;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Set;


@Slf4j
@Service
public class MqttMessageCallBack implements MqttCallback {


    @Lazy
    @Resource
    private  MqttClient mqttClient;

    @Lazy
    @Resource
    MqttMessageListener mqttMessageListener;

    @Override
    public void connectionLost(Throwable throwable) {
    	log.error("mqtt断开连接，正在尝试重连mqtt服务器...", throwable);
        while (true) {
            try {
                // 每10秒重连一次
                Thread.sleep(10000);
                if (!mqttClient.isConnected()) {
                    mqttClient.connect();
                    // 创建 Reflections 实例，用于扫描包
                    Reflections reflections = new Reflections("com.ruoyi.iot.handler");
                    // 获取包下所有带有 MqttSubscribeService 注解的类
                    Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(com.ruoyi.iot.config.MqttSubscribeService.class);
                    // 遍历找到的类并输出 topic 值
                    for (Class<?> clazz : annotatedClasses) {
                        com.ruoyi.iot.config.MqttSubscribeService annotation = clazz.getAnnotation(com.ruoyi.iot.config.MqttSubscribeService.class);
                        if (annotation != null) {
                            mqttClient.subscribe(annotation.topic(), mqttMessageListener);
                            log.info("订阅topic: {}",annotation.topic());
                        }
                    }
                }else{
                    log.info("重新连接mqtt服务器成功！！！");
                    break;
                }
            } catch (Exception e) {
                log.error("正在尝试重连mqtt服务器...");
            }
        }
    }


    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {

	}
}
